package com.tulele.vtool.task.async;

import com.alibaba.fastjson.JSONObject;
import com.tulele.vtool.bus.mapper.log.PushDetailLogMapper;
import com.tulele.vtool.bus.mapper.log.PushHeadLogMapper;
import com.tulele.vtool.bus.model.UserInfo;
import com.tulele.vtool.bus.model.log.PushDetailLog;
import com.tulele.vtool.bus.model.thirdparty.WxNotifyMsgSetInfo;
import com.tulele.vtool.bus.model.thirdparty.WxPushUserInfo;
import com.tulele.vtool.bus.service.*;
import com.tulele.vtool.model.PlatformSysInfo;
import com.tulele.vtool.model.UserGroupOpenId;
import com.tulele.vtool.util.RedisCacheUtil;
import com.tulele.vtool.util.SpringContextUtil;
import com.tulele.vtool.util.SysConstant;
import com.tulele.vtool.util.ToolUtil;
import com.tulele.vtool.wechat.service.WeixinService;
import com.tulele.vtool.wechat.service.WeixinServiceDL;
import com.tulele.vtool.wechat.service.WeixinServiceMap;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.bean.kefu.WxMpKefuMessage;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateData;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateMessage;
import org.springframework.beans.factory.ObjectFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.Optional;
//6:10 文章推送
@Component
@Slf4j
public class FirstTimeArticlePushAsyncTask {

    @Autowired
    private RedisCacheUtil redisCacheUtil;

    @Autowired
    private IArticleService articleService;

    @Autowired
    private IArticleProfessionalService articleProfessionalService;

    @Autowired
    private ObjectFactory<WeixinServiceDL> objectFactory;

    @Autowired
    private SysGzhService sysGzhService;

    @Autowired
    private IUserService userService;

    @Autowired
    private PushDetailLogMapper pushDetailLogMapper;

    @Value("${Professional}")
    private String professional;//专业号

    @Autowired
    private UserGroupGzhService userGroupGzhService;


    //20200401 hyl 改成同步发 因为多线程 数据库顶不住
    //20200512 调整参数，多线程跑
    @Async("taskExecutor")
    public Integer execute(String redisKey, Integer headId, UserInfo userInfo,String profile) throws Exception {

        Integer ret = 2;

        WxPushUserInfo wxPushUserInfo  = new WxPushUserInfo();
        wxPushUserInfo.setOpenId(userInfo.getOpenId());

        UserGroupOpenId ugoId = userGroupGzhService.getUserOpenId(profile, userInfo.getUserId());
        if (ugoId != null) {
            wxPushUserInfo.setOpenId(ugoId.getOpenId());
        }

        wxPushUserInfo.setUserId(userInfo.getUserId());

        if (wxPushUserInfo != null) {

            WxNotifyMsgSetInfo wxNotifyMsgSetInfo = userService.getUserWxMsgAcceptSwitchInfo(wxPushUserInfo.getUserId());

            int firstTimeArticleAcceptStatus = Optional.ofNullable(wxNotifyMsgSetInfo.getFirstTimeArticleAcceptStatus()).orElse(1);

            if (firstTimeArticleAcceptStatus == 1) {
                String kefuMsg ="";
                if(professional.contains(profile)) {//专业号
                    kefuMsg = articleProfessionalService.generateUserPushArticleInfoFirstTime(wxPushUserInfo.getUserId(), profile);
                }else{
                    kefuMsg = articleService.generateUserPushArticleInfoFirstTime(wxPushUserInfo.getUserId(), profile);
                }

                if (!kefuMsg.equals("")) {
                    if(userInfo.getPhoneModel().equals(SysConstant.IOS)){
                        kefuMsg = ToolUtil.handleMsgmenuidByIOS(kefuMsg);
                    }
                    WxMpKefuMessage message = WxMpKefuMessage.TEXT().toUser(wxPushUserInfo.getOpenId()).content(kefuMsg).build();

                    PushDetailLog pushDetailLog = new PushDetailLog();
                    pushDetailLog.setGzhCode(profile);
                    pushDetailLog.setUserId(wxPushUserInfo.getUserId());
                    pushDetailLog.setMsgType(1);
                    pushDetailLog.setPushTime(new Date());
                    pushDetailLog.setHeadId(headId);
                    pushDetailLog.setOpenId(wxPushUserInfo.getOpenId());

                    try {
                        WeixinServiceDL weixinService= WeixinServiceMap.getWeixinService(profile);
                        if(weixinService==null) {
                            weixinService = objectFactory.getObject();
                            weixinService.reSetConfigStorage(profile);
                            WeixinServiceMap.putWeixinService(profile,weixinService);
                        }
                        Boolean sendRet = weixinService.getKefuService().sendKefuMessage(message);
                        if (sendRet) {
                            ret = 0;
                            pushDetailLog.setMsg("成功");
                        } else {
                            ret = 1;
                            pushDetailLog.setMsg("失败");
                        }
                    } catch (WxErrorException e) {
                        ret = 2;
                        //e.printStackTrace();
                        pushDetailLog.setMsg(e.getMessage());
                    }
                    pushDetailLog.setResult(ret);

                    pushDetailLogMapper.addPushDetailLog(pushDetailLog);
                }
            }
        }

        return ret;

//        log.info("[exit FirstTimeArticlePushAsyncTask] = " + redisKey);

    }

    public Integer execute2(String redisKey,UserInfo userInfo,String profile) throws Exception {

        Integer ret = 2;

        WxPushUserInfo wxPushUserInfo  = new WxPushUserInfo();
        wxPushUserInfo.setOpenId(userInfo.getOpenId());

        UserGroupOpenId ugoId = userGroupGzhService.getUserOpenId(profile, userInfo.getUserId());
        if (ugoId != null) {
            wxPushUserInfo.setOpenId(ugoId.getOpenId());
        }

        wxPushUserInfo.setUserId(userInfo.getUserId());

        if (wxPushUserInfo != null) {

            WxNotifyMsgSetInfo wxNotifyMsgSetInfo = userService.getUserWxMsgAcceptSwitchInfo(wxPushUserInfo.getUserId());

            int firstTimeArticleAcceptStatus = Optional.ofNullable(wxNotifyMsgSetInfo.getFirstTimeArticleAcceptStatus()).orElse(1);

            if (firstTimeArticleAcceptStatus == 1) {
                String kefuMsg = articleService.generateUserPushArticleInfoFirst(wxPushUserInfo.getUserId(),profile);
                if (!kefuMsg.equals("")) {
                    if(userInfo.getPhoneModel().equals(SysConstant.IOS)){
                        kefuMsg = ToolUtil.handleMsgmenuidByIOS(kefuMsg);
                    }
                    WxMpKefuMessage message = WxMpKefuMessage.TEXT().toUser(wxPushUserInfo.getOpenId()).content(kefuMsg).build();

                    try {
                        WeixinServiceDL weixinService= WeixinServiceMap.getWeixinService(profile);
                        weixinService.getKefuService().sendKefuMessage(message);
                    } catch (WxErrorException e) {
                        ret = 2;
                    }
                }
            }

        }

        return ret;

    }

}
